import { specslist, specscount } from '../../request/api'
const state = {
    list: [],
    // 总个数
    count: 0,
    // 页数
    page: 1,
    // 每页个数
    size: 2
}

const mutations = {
    changelist(state, arr) {
        state.list = arr
    },
    changecount(state, num) {
        state.count = num
    },
    changepage(state, num) {
        state.page = num
    }
}

const actions = {
    reqchangelist(context,flag) {        
        let data=flag?{}:{ size: context.state.size, page: context.state.page }
        specslist(data).then(res => {
            let list = res.data.list ? res.data.list : []
            if (list.length == 0 && context.state.page > 1) {
                context.commit('changepage', context.state.page - 1)
                context.dispatch('reqchangelist')
            }
            list.forEach(item => item.attrs = JSON.parse(item.attrs))
            context.commit('changelist', list)
        })
    },
    reqchangecount(context) {
        specscount().then(res => {
            // console.log(res.data.list[0]);
            context.commit('changecount', res.data.list[0].total)
        })
    },
    reqchangepage(context, num) {
        context.commit('changepage', num)
        // 刷新列表
        context.dispatch('reqchangelist')
    }
}

const getters = {
    list(state) {
        return state.list
    },
    count(state) {
        return state.count
    },
    page(state) {
        return state.page
    },
    size(state) {
        return state.size
    }
}

export default {
    state,
    mutations,
    actions,
    getters,
    namespaced: true
}